/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package psexecute;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author Gerratana Francesco
 */
public class CmdExecuter {
    private final int NO_EXE_FOUND = 0;
    private final int ERROR_OUTPUT = -1;
    private final int NO_ERROR_OUTPUT = 1;
    private StringBuilder output = new StringBuilder();

    public String getOutput() {
        return output.toString();
    }
    private String[] cmd = new String[3];

    public CmdExecuter() {
        cmd[0] = "cmd.exe";
        cmd[1] = "/C";
    }

    public CmdExecuter(String executable) {
        this();
        this.setExecutable(executable);
       }

    private void setExecutable(String executable) {
        cmd[2] = executable;
    }

    private String catchOutput(InputStreamReader isr) throws IOException {
        StringBuilder outputString = new StringBuilder();
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        StringBuilder sb = new StringBuilder("");
        //Valorizzazione output eseguibile
        while ((line = br.readLine()) != null) {
            outputString.append(line).append("\n");
        }

        return outputString.toString();
    }

    public int launch(String executable) throws IOException {
        this.setExecutable(executable);
        return this.launch();
    }

    public int launch() throws IOException {
        if (cmd[2].isEmpty()) {
            return this.NO_EXE_FOUND;
        } else {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(cmd);
            InputStreamReader isr = new InputStreamReader(proc.getInputStream());
            InputStreamReader eisr = new InputStreamReader(proc.getErrorStream());
            String stdout = this.catchOutput(isr);
            String errout = this.catchOutput(eisr);
            this.output.append(stdout).append(errout);
            return (!errout.isEmpty()) ? this.ERROR_OUTPUT : this.NO_ERROR_OUTPUT;
        }

    }
}
